<template>
  <el-dialog
  :visible.sync="currentVisible"
  :close-on-click-modal="false"
  :modal="true"
  :destroy-on-close="true"
  :append-to-body="true"
  title="Select Dashboard"
>
<template>
  <div class="body">
    <div class="header">
      <el-input  v-model="inputStr" class="input-with-select"  suffix-icon="el-icon-search"  @input="keyWordsChange" placeholder="Search">
      </el-input>
    </div>
    <div class="content" v-loading = loading||widgetInfoLoading >
      <el-radio-group v-model="radio" class="radio" v-for="(item) in reportList" :key="item.id">
       <div class='radio-group-item'><el-radio :label="item.id">{{ item.name }}</el-radio></div>
      </el-radio-group>
    </div>

  </div>
  
</template>

<span slot="footer" class="dialog-footer">
    <el-button type="primary" @click="onClone" class="cloneButton" size='small' :loading ="cloneSuccessLoading">Clone</el-button>
</span>
</el-dialog>
</template>

<script>
import { getGadget } from '@/components/storybook/hooks/useGadget'
import { fetchReportList } from '@/api/new'
import { debounce } from 'lodash'
import bus from '@/components/storybook/utilties/bus'
import { v4 } from 'uuid'
import {filterRole} from '@/utils/common'
export default {
data() {
  return {
    reportList: [],
    loading: false ,
    radio: 3,
    inputStr: '',
    cloneWidgetInfo: {},
    cloneSuccessLoading: false,
  }
},
props: {
  visible: {
    type: Boolean,
    default: false
  },
  widgetInfoLoading:{
    type: Boolean,
    default: true
  },
  widgetInfo:{
    type: Object,
    default: () => ({})
  }
},
computed: {
    currentVisible: {
      get () {
        return this.visible
      },
      set (val) {
        this.$emit('update:visible', val)
      }
    }
  },
created() {
  this.init()
},
methods: {
 async init() {
    try {
        this.loading = true
        const report = await this.getReportList()
        this.reportList = report.records

      } catch (error) {
      } finally {
        this.loading = false
      }
  },
  async getReportList () {
       try {
        const params = {
        current: 1,
        internal: false,
        layoutType: "report_layout",
        integrationGroup: [],
        filter:{},
        name:this.inputStr,
        myFavorite: false,
        order: [{sort: "DESC", field: "update_date"}],
        orderField: '',
        queryType: null,
        resourceType: 0,
        showAllIntegration: false,
        size: 100
      }
      this.selectLoading = true
      const { data: response } = await fetchReportList(params)
      if (response.code !== 0) {
        throw response.msg
      }
      this.selectLoading = false
      return response.data || {}
     
       } catch (error) {
        this.selectLoading = false
       }
    },
    keyWordsChange: debounce(async function () {
      try {
        this.loading = true
        const report = await this.getReportList()
        this.reportList = report.records
      } catch (error) {
      } finally {
        this.loading = false
      }
  
    }, 1000),
  onClone() {
    this.onClonebefore().then(() => {
      let data = this.reportList.find(item => item.id === this.radio)
    if (!data) {
      return
    }
    localStorage.setItem(`clonerefresh`,'true')
    localStorage.setItem(`cloneWightToDashboards-${data.id}`,JSON.stringify(getGadget(this.cloneWidgetInfo)))
    if (data.layoutType === 'report_layout') {
            this.$router.push({
              path: `dashboard-${data.id}`,
              query: {
                pageid: data.id,
                name: data.name,
                layout: data.layoutType,
              }
            })
          } else {
            this.$router.push({
              path: `report-${data.id}`,
              query: {
                pageid: data.id,
                name: data.name,
                layout: data.layoutType
              }
            })
          }

    // localStorage.removeItem(`cloneWidget`)      
    this.currentVisible = false
       
    }).catch((error) => {
      thuis.$message.error(error) 
      // this.currentVisible = false
    })
 
  },
  async onClonebefore () {
      try {
        let form =  this.widgetInfo
        if (
          this.$store.state.user.username.includes('mspbots.ai') &&
          this.$hasPermission('sys:widget:moreedit')
        ) {
          if (!form.da) {
            return this.$message.error(this.$t('custom.component.gadget.da'))
          }
          if (!form.po) {
            return this.$message.error(this.$t('custom.component.gadget.po'))
          }
         
          if (!form.jiraNumber) {
            return this.$message.error(
              this.$t('custom.component.gadget.checkNumber')
            )
          }
        }
        this.cloneSuccessLoading=true
        const { postWidgetCloneDataApi } = this.$interface.reports
 
        const params = {
          ...form,
          name: `${form.name}_clone_${moment().utc().format()}`,
          resourceType: 1,
          gadgetId: v4()
        }
        params.roleIdList = await filterRole(params.roleIdList)
        const { data: response } = await postWidgetCloneDataApi(params)
        if (response.code !== 0) {
          throw response.msg
        }
        this.cloneWidgetInfo = response.data
        this.cloneSuccessLoading=false

      } catch (error) {
        this.cloneSuccessLoading=false
        console.log(error);
      }
    }
}

}
</script>
<style lang="scss" scoped>
::v-deep .el-dialog  {
width: 526px !important;
}
::v-deep .el-dialog__body {
  padding: 15px;
  word-break: break-word;
  border-top: 1px solid #DDE1E6;
  height: 573px;
}
::v-deep .el-dialog__footer {
  border-top: 1px solid #DDE1E6;
}
::v-deep .el-dialog__title {
// font-size: 18px;
font-weight: bold;
color: #262626;
}
// ::v-deep .el-dialog__headerbtn .el-dialog__close {
// color: #262626;
// }
.input-with-select {
  width: 35%;
  float: right;
  margin-right: 10px
}
.header {
  height: 45px;
  width: 100%;
  line-height: 45px;
  border-bottom: 1px solid #DDE1E6;
  background-color: #f2f4f8;
}
.body {
  border: 1px solid #DDE1E6;
  border-radius: 4px;
  width: 100%;
  height: 100%;

}

.radio { 
  display: flex;
  flex-direction: column;

}
.content {
  height: 495px;
  overflow-y: auto;
}
.cloneButton {
  background-color: #0043ce;
}
.radio-group-item {
  height: 40px;
    padding-top: 4px;
    line-height: 40px;
    padding-left: 5px;
    border-top: 1px solid #DDE1E6;
    overflow: hidden;
}

</style>
